package com.fishleap.sqlSession;

import com.fishleap.pojo.Configuration;
import com.fishleap.pojo.MapperStatement;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

/**
 * @author zlg
 * @create 2020-04-22 1:11
 */
public class SimpleExecutor implements Executor {

    // 编写 jdbc 操作数据库
    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
        /**
         * 由于增删改查在执行sql时都需要以下几步: 故封装为 PreparedStatementHandler设置参数
         * 1.获取Connection连接对象
         * 2.获取解析后的sql
         * 3.根据sql获取预处理对象PreparedStatement
         * 4.使用反射设置参数
         */
        PreparedStatementHandler preparedStatementHandler = new PreparedStatementHandler(configuration, mapperStatement, params);
        PreparedStatement preparedStatement = preparedStatementHandler.getPreparedStatement();

        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        /**
         * ResultSetHandler: 使用内省封装结果集
         */
        ResultSetHandler resultSetHandler = new ResultSetHandler(mapperStatement, resultSet);
        return resultSetHandler.getResultSet();
    }


    @Override
    public void update(Configuration configuration, MapperStatement mapperStatement, Object[] params) throws Exception {
        // 获取设置好参数的PreparedStatementHandler
        PreparedStatementHandler preparedStatementHandler = new PreparedStatementHandler(configuration, mapperStatement, params);
        PreparedStatement preparedStatement = preparedStatementHandler.getPreparedStatement();
        // 执行增/删/改操作
        preparedStatement.executeUpdate();
    }


    // insert/delete可以不同写
    @Override
    public void insert(Configuration configuration, MapperStatement mapperStatement, Object[] params) throws Exception{
        update(configuration,mapperStatement,params);
    }

    @Override
    public void delete(Configuration configuration, MapperStatement mapperStatement, Object[] params) throws Exception {
        update(configuration,mapperStatement,params);
    }


}
